package com.say.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.say.bean.common.Response;
import com.say.bean.common.SplitPage;
import com.say.bean.domain.Chat;
import com.say.bean.domain.Message;
import com.say.bean.domain.Trace;
import com.say.bean.domain.User;
import com.say.service.ChatService;
import com.say.service.MessageService;
import com.say.service.TraceService;
import com.say.service.UserService;
import com.say.utils.UserUtil;

@Controller
@RequestMapping("/wensay/chat")
public class ApiChatController extends BaseController {

	@Autowired
	protected ChatService chatService;
	
	@Autowired
	protected UserService userService;
	
	@Autowired
	protected MessageService messageService;
	
	@Autowired
	protected TraceService traceService;
	
	
	//聊天页面
	@RequestMapping()
	public String say(Model model,String toUserId){
		User user = UserUtil.getUser(request);
		model.addAttribute("user", userService.getById(user.getId()));
		model.addAttribute("toUser", userService.getById(toUserId));
		try {
			if(user!=null && StringUtils.isNotEmpty(user.getId())) {
				Chat chat=new Chat();
				chat.setUserId(user.getId());
				chat.setToUserId(toUserId);
				chat.setType(5);
				chat.setText("TA打开消息");
				chat.setStatus(1);
				chat.setCreateTime(new Date());
				chatService.save(chat);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		traceService.save(new Trace(user.getId(),"0.0.0.0","访问聊天页面"));
		return "wensay/chat";
	}
	
	@RequestMapping("/page")
	@ResponseBody
    public Response page(Model model,int pageSize,int pageNo,String toUserId,String maxChatId) {
		Response response = new  Response();
		User user = UserUtil.getUser(request);
		String userId=user.getId();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("toUserId", toUserId);
        params.put("maxChatId", maxChatId);
       
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = chatService.findChatByPage(params, initPage(pageNo, pageSize));
        for (Map<String, Object> map : page.getContent()) {
        	if(userId.equals(map.get("user_id").toString())) {
        		map.put("isown",1);
        	}else {
        		map.put("isown",2);
        	}
		}
        sp.setRowCnt((int) page.getTotalElements());
        messageService.clearUnReadMessageByUser(toUserId, userId);
        response.success(page,"查询成功");
		return response;
    }
	
	
	@RequestMapping("/interval/page")
	@ResponseBody
    public Response intervalPage(Model model,String toUserId,String maxChatId) {
		Response response = new  Response();
		User user = UserUtil.getUser(request);
		String userId=user.getId();
        List<Chat> chats = chatService.findChatByIntervalPagePage(userId,toUserId,maxChatId);
        messageService.clearUnReadMessageByUser(toUserId, userId);
        response.success(chats,"查询成功");
		return response;
    }
	
	
	

	@RequestMapping(value="/save")
	@ResponseBody
	public Response saveMerchantPlat(Model model,String toUserId,Integer type,String text) { 
		Response response = new  Response();
		User user = UserUtil.getUser(request);
		String userId=user.getId();
		
		Chat chat=new Chat();
		chat.setUserId(userId);
		chat.setToUserId(toUserId);
		chat.setType(type);
		chat.setText(text);
		chat.setStatus(1);
		chat.setCreateTime(new Date());
		chatService.save(chat);
		
		try {
			Message message=messageService.getMessageByUserIdAndToUserId(userId, toUserId);
			if(message!=null) {
				messageService.saveUnReadMessageById(message.getId(), message.getUnRead()+1, text);
			}else {
				message=new Message();
				message.setStatus(1);
				message.setUserId(userId);
				message.setToUserId(toUserId);
				message.setText(text);
				message.setUnRead(1);
				message.setUpdateTime(new Date());
				messageService.save(message);
			}
			
			message=messageService.getMessageByUserIdAndToUserId(toUserId, userId);
			if(message!=null) {
				messageService.saveUnReadMessageById(message.getId(), message.getUnRead(), text);
			}else {
				message=new Message();
				message.setStatus(1);
				message.setUserId(toUserId);
				message.setToUserId(userId);
				message.setText(text);
				message.setUnRead(0);
				message.setUpdateTime(new Date());
				messageService.save(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.success("操作成功");
		return response;
	}
	
	
	


}
